package com.yanqu.road.server.cmd.union;

import com.yanqu.road.server.pb.UnionPb;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.union.UnionMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.command.Cmd;

import java.util.Map;

//@Cmd(code = Protocol.S_UNION_SEARCH, desc = "查找商会")
public class SearchUnionCmd extends AbstractCommand {

	private long unionAliasId;

	private UnionInfo unionInfo;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		UnionProto.UnionSearchReqMsg reqMsg = UnionProto.UnionSearchReqMsg.parseFrom(packet.getBytes());
		unionAliasId = reqMsg.getUnionAliasId();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		unionInfo = UnionMgr.searchUnion(unionAliasId);
		if(null == unionInfo){
			ret = GameErrorCode.E_UNION_NO_FOUND;
		}
	}

	@Override
	public void sendData(GamePlayer player) {
		UnionProto.UnionSearchRespMsg.Builder respMsg = UnionProto.UnionSearchRespMsg.newBuilder();
		respMsg.setRet(ret);
		if(0 == ret){
			respMsg.setUnion(UnionPb.parseUnionTempMsg(unionInfo));

			Map<Long, UnionMember> memberMap = UnionMgr.getUnionMemberMap(unionInfo.getUnionUid());
			if (null != memberMap) {
				for (UnionMember member : memberMap.values()) {
					UnionProto.UnionMemberTempMsg.Builder memberMsg = UnionPb.parseUnionMemberTempMsg(member);
					if(null != memberMsg) {
						respMsg.addMemberList(memberMsg);
					}
				}
			}
		}
		player.sendPacket(Protocol.U_UNION_SEARCH, respMsg);
	}

}
